package com.sgr.controllers;

import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sgr.model.Acesso;
import com.sgr.services.AcessoService;

@Controller
@RequestMapping("/")
public class AcessoController {
	
	@Autowired
	private AcessoService acessoService;
	
	public void setAcessoService(AcessoService acessoService){
		this.acessoService = acessoService;
	}
	
	@RequestMapping(value="/home")
	public String Home(){
		Long users = acessoService.count();
		return users == 0 ? "/home" : "/listaAcesso" ;
	}
	
	@RequestMapping(value="/addCustomer", method=RequestMethod.POST)
	public String addCustomer(@RequestParam(value="login")String login, @RequestParam(value="senha")String senha){
		Acesso acesso = new Acesso();
		acesso.setLogin(login);
		acesso.setSenha(senha);
		try{
			acessoService.save(acesso);
			return "/listaAcesso";
		}catch (ConstraintViolationException e){
			return "/listaAcesso";
		}
	}
	
	@RequestMapping(value="/delete", method=RequestMethod.GET)
	public String delete(@RequestParam(value="id")int id){
		acessoService.delete(id);
		return "/listaAcesso";
	}

}
